// © Coff3eG
//@version=5

indicator("Gaussian SWMA For Loop", overlay = true)

// Input Params
length = input.int(4, title = "WMA Length", minval = 1, group = "Main")
len    = input.int(2, title = "SMA Length", minval = 1, group = "Main")
src    = input(close, title = "Source", group = "Main")
sigma  = input.float(2.0, title = "Gaussian Sigma", minval = 0.1, step = 0.1, group = "Main") // Standard deviation for Gaussian filter

// Gaussian Filter Function
gaussian_filter(src, length, sigma) =>
    gaussian_sum = 0.0
    gaussian_weighted_sum = 0.0
    for i = 0 to length - 1
        weight = math.exp(-0.5 * math.pow((i - (length - 1) / 2) / sigma, 2))
        gaussian_sum := gaussian_sum + weight
        gaussian_weighted_sum := gaussian_weighted_sum + src[i] * weight
    gaussian_weighted_sum / gaussian_sum

// Apply Gaussian Filter
gaussian_smooth = gaussian_filter(src, length, sigma)

// Calc SMA on Gaussian Filtered Data
filtered_sma = ta.sma(gaussian_smooth, len)

a      = input.int(1, title = "From", group = "For Loop", minval = 1)
b      = input.int(50, title = "To", group = "For Loop", maxval = 50)

system(a, b) =>
    total  = 0.0
    for i  = a to b by 1
        total += (filtered_sma > filtered_sma[i] ? 1 : -1)
        total
    total

score = system(a, b)

threshold_L = input.int(40, title = "Long Threshold", group = "Threshold")
threshold_S = input.int(0, title = "Short Threshold", group = "Threshold")

L      = score > threshold_L
S      = score < threshold_S

Coff = 0
if L and not S
    Coff := 1

if S
    Coff := -1


a_plot = plot(filtered_sma, color = color.rgb(0, 255, 187, 100))
b_plot = plot(filtered_sma[1], color = color.rgb(0, 255, 187, 100))
fill(a_plot, b_plot, color = Coff ==  1  ?  color.rgb(0, 255, 187) : Coff == -1  ?  color.rgb(255, 0, 157) : color.gray)

// plot(filtered_sma, "Filtered SMA", color = Coff ==  1 ? color.rgb(0, 255, 187) : Coff ==  -1 ? color.rgb(255, 0, 157) : color.gray, linewidth = 2)
barcolor(color = Coff ==  1 ? color.rgb(0, 255, 187) : Coff ==  -1 ? color.rgb(255, 0, 157) : color.gray)

alertcondition(L, title="Gaussian SWMA Long", message="Gaussian SWMA Long on {{exchange}}:{{ticker}}")
alertcondition(S, title="Gaussian SWMA Short", message="Gaussian SWMA Short on {{exchange}}:{{ticker}}")

